Finally solved it! Though the algorithm is still pretty ugly, so I'll still reverse-engineer the examples in the stackoverflow link posted earlier.
If you're curious, my code (you can just copy-paste it into a .cpp and compile it): show at bpaste
Could a moderator please mark this thread as solved?